import pygame
import sys
import json
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from config.game_config import GameConfig

class ObstacleEditor:
    """障碍物编辑器"""
    
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((GameConfig.SCREEN_WIDTH, GameConfig.SCREEN_HEIGHT))
        pygame.display.set_caption("Ball Battle - Obstacle Editor")
        self.clock = pygame.time.Clock()
        
        # 颜色定义
        self.BLACK = (0, 0, 0)
        self.WHITE = (255, 255, 255)
        self.GRAY = GameConfig.OBSTACLE_COLOR
        self.GREEN = (0, 255, 0)
        
        # 编辑器状态
        self.obstacles = []  # [(x, y, width, height), ...]
        self.drawing = False
        self.current_rect = None
        self.brush_size = 20
        
        # 字体
        self.font = pygame.font.Font(None, 36)
        
    def handle_events(self):
        """处理事件"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False
                
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # 左键
                    self.drawing = True
                    x, y = event.pos
                    self.current_rect = [x, y, 1, 1]
                    
            elif event.type == pygame.MOUSEBUTTONUP:
                if event.button == 1:  # 左键释放
                    if self.drawing and self.current_rect:
                        # 添加障碍物
                        rect = pygame.Rect(self.current_rect)
                        if rect.width > 0 and rect.height > 0:
                            self.obstacles.append((rect.x, rect.y, rect.width, rect.height))
                    self.drawing = False
                    self.current_rect = None
                    
            elif event.type == pygame.MOUSEMOTION:
                if self.drawing and self.current_rect:
                    x, y = event.pos
                    self.current_rect[2] = x - self.current_rect[0]  # width
                    self.current_rect[3] = y - self.current_rect[1]  # height
                    
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_s:  # 保存
                    self.save_obstacles()
                elif event.key == pygame.K_l:  # 加载
                    self.load_obstacles()
                elif event.key == pygame.K_c:  # 清空
                    self.obstacles.clear()
                elif event.key == pygame.K_UP:  # 增大画笔
                    self.brush_size = min(100, self.brush_size + 5)
                elif event.key == pygame.K_DOWN:  # 减小画笔
                    self.brush_size = max(5, self.brush_size - 5)
                    
        return True
        
    def update(self):
        """更新状态"""
        pass
        
    def render(self):
        """渲染画面"""
        self.screen.fill(self.BLACK)
        
        # 绘制已有的障碍物
        for obstacle in self.obstacles:
            pygame.draw.rect(self.screen, self.GRAY, obstacle)
            
        # 绘制正在绘制的矩形
        if self.drawing and self.current_rect:
            rect = pygame.Rect(self.current_rect)
            pygame.draw.rect(self.screen, self.GRAY, rect, 2)
            
        # 绘制UI信息
        instructions = [
            "Left Click & Drag: Draw obstacles",
            "S: Save obstacles",
            "L: Load obstacles", 
            "C: Clear all obstacles",
            "UP/DOWN: Brush size ({})".format(self.brush_size),
            "ESC: Quit"
        ]
        
        for i, text in enumerate(instructions):
            text_surface = self.font.render(text, True, self.WHITE)
            self.screen.blit(text_surface, (10, 10 + i * 30))
            
        pygame.display.flip()
        
    def save_obstacles(self):
        """保存障碍物到文件"""
        data = {
            "obstacles": self.obstacles
        }
        
        with open("maps/default_map.json", "w") as f:
            json.dump(data, f, indent=2)
            
        print("Obstacles saved to maps/default_map.json")
        
    def load_obstacles(self):
        """从文件加载障碍物"""
        if os.path.exists("maps/default_map.json"):
            try:
                with open("maps/default_map.json", "r") as f:
                    data = json.load(f)
                    self.obstacles = data.get("obstacles", [])
                print("Obstacles loaded from maps/default_map.json")
            except Exception as e:
                print(f"Error loading obstacles: {e}")
                
    def run(self):
        """运行编辑器"""
        # 创建maps目录
        os.makedirs("maps", exist_ok=True)
        
        running = True
        while running:
            running = self.handle_events()
            self.update()
            self.render()
            self.clock.tick(GameConfig.FPS)
            
        pygame.quit()
        sys.exit()

if __name__ == "__main__":
    editor = ObstacleEditor()
    editor.run()